import parent_default from '../Img/other/headerImgDefault.png'; //parent_default.png
import teacher_default from '../Img/other/headerImgDefault.png'; //teacher_default.png
import splitImg from '../Img/other/splitImg.jpg';
import loadImgUrl from '../Img/icon/load.gif';

import LoadingBox from '../Comment/Common/LoadingBox';
import LazyLoadImg from 'lazy-load-img';
import imgKb from '../Img/mall/kb.gif';
import $ from 'jquery'

//线上线下切换
const online = true//线上
// const online = false //线下

//默认线上地址
export let sxtUrl = 'http://api.17find.com'; //随寻通接口地址
export let sxtPageUrl = 'http://wx.17find.com'; //随寻通页面地址
export let jxtUrl = 'http://sxt.17find.com'; //家校通地址
export let phpUrl = 'http://101.37.77.7'; //PHP文件管理地址

if (!online) {
    sxtUrl = 'http://192.168.2.12:8800';
    // sxtUrl = ''; //代理地址

    sxtPageUrl = 'http://192.168.2.31:1234';

    // jxtUrl = 'http://192.168.2.11:1780';
    jxtUrl = 'http://192.168.2.31:1235'

    phpUrl = 'http://192.168.2.12:1235';
}

//图片使用地址
export const AjaxUploadImgUrl = phpUrl + '/php/filedownload_image.php?FileId=';

//家校通入口页面参数
export let jxtUrlData;

/**
 * 判断是否有特殊字符
 * @param str
 * @returns {boolean}
 */
export const specialStr = (str) => {
    str = str.replace(/\s/ig, '');
    return !/^[a-zA-Z0-9\u4E00-\u9FA5]+$/ig.test(str)
};
/**
 * 时间戳转时间格式
 * @param number
 * @returns {string}
 */
export const getLocalTime = (number = 0) => {
    return dateFormat(new Date(number))
};
/**
 * 时间字符串格式统一
 * @param str
 * @returns {string}
 */
export const dateStrFormat = (str) => {
    if (str == undefined)
        str = '';
    return (str + '').replace(/\-/g, '.').replace(/\//g, '.')
};

/**
 * 时间保持2位，加零处理
 * @param num
 * @returns {*}
 */
export const allUnit = (num) => {
    if (num < 10)
        num = '0' + num;
    return num;
};

/**
 * 时间格式处理
 * @param time
 * @param newSplit
 * @param all
 * @returns {string}
 */
export const dateFormat = (time, newSplit = '.', all = true) => {
    let nowTime = new Date();
    let year = time.getFullYear(),
        month = time.getMonth() + 1, //月
        date = time.getDate(), //日
        hours = time.getHours(), //时
        minute = time.getMinutes(), //分
        seconds = time.getSeconds(); //秒
    //当前时间
    let day = year + newSplit + allUnit(month) + newSplit + allUnit(date);
    if (newSplit == '.') {
        if (nowTime.toLocaleString().split(' ')[0].replace(/\//g, '-') == time.toLocaleString().split(' ')[0].replace(/\//g, '-')) {
            day = '今天'
        } else {
            nowTime = new Date(nowTime.setDate(nowTime.getDate() - 1));
            if (nowTime.toLocaleString().split(' ')[0].replace(/\//g, '-') == time.toLocaleString().split(' ')[0].replace(/\//g, '-')) {
                day = '昨天'
            } else if (nowTime.getFullYear() == time.getFullYear()) {
                day = allUnit(month) + newSplit + allUnit(date);
            }
        }
    }
    if (all)
        day += ' ' + allUnit(hours) + ':' + allUnit(minute);

    return day;
};

/**
 * 获取时间 传入数字 -1 前一天
 * @param AddDayCount
 * @param dd
 * @constructor
 */
export const GetDateStr = (AddDayCount, dd = new Date()) => {
    dd.setDate(dd.getDate() + AddDayCount);
    return dateFormat(dd, '-', false)
};

//处理无网络时样式
export const InternetStyle = () => {
    if (document.querySelector('.datastatus')) {
        document.querySelector('.datastatus').innerHTML = '<span class="no">网络连接失败</span>'
        if (document.querySelector('.h_link'))
            document.querySelector('.h_link').style.display = 'none'
        if (document.querySelector('.type_list'))
            document.querySelector('.type_list').style.display = 'none'
        if (document.querySelector('.h_title span') && document.querySelector('.h_title span').innerText == '') {
            document.querySelector('.h_title span').style.display = 'none'
            if (document.querySelector('.sltbox'))
                document.querySelector('.sltbox').style.display = 'none'
        }
        // document.querySelector('.h_back').onclick = function() {
        //     if (sessionStorage.app == 'true') {
        //         location.href = '/appback'
        //     }
        // }
    } else {
        setTimeout(() => {
            InternetStyle()
        }, 600)
    }
};


/**
 * Ajax请求
 */
export class HttpService {
    static query(config = {}) {
        if (sessionStorage.internet == 0)
            return
        if (config.async == undefined)
            config.async = true;
        var request = new XMLHttpRequest();
        var sign = config.url.indexOf('?') > -1 ?
            '&' :
            '?';
        var data = HttpService.formatParams(config.data)
        if (data != '' && !/^[\s+`~!@#$%^&*()\-=_+[\]{};'\\:"|,.<>/?？·！￥…（）—【】；‘’、“”：，。《》、a-zA-Z0-9\u4E00-\u9FA5]+$/ig.test(data)) {
            config.success({
                code: 99
            });
            Tips('提交内容有特殊字符')
            return
        }
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                var status = request.status;
                if (status == 200) {
                    let res = request.responseText;
                    try {
                        res = JSON.parse(res);
                    } catch (e) {
                        if (res.indexOf('?xml') > -1) {
                            res = JSON.parse(xmlToJson(res).replace(/[\n]/ig, ''));
                        }
                    } finally {
                        config.success(res);
                    }
                } else {
                    sessionStorage.internet = 0
                    setTimeout(() => {
                        delete sessionStorage.internet
                    }, 800)
                    if (config.fail) {
                        return config.fail(status);
                    } else {
                        Tips('网络连接错误');
                    }
                    InternetStyle()
                }
            }
        };

        if (config.type == 'post') {
            request.open('POST', config.url, config.async);
            request.send(config.data);
        } else {
            request.open('GET', config.url + sign + HttpService.formatParams2(config.data), config.async);
            request.send(null);
        }
    }
    static formatParams(data) {
        var arr = [];
        for (var name in data) {
            arr.push(name + "=" + data[name]);
        }
        arr.push(("ver=" + Math.random()).replace(".", ""));
        return arr.join("&");
    }
    static formatParams2(data) {
        var arr = [];
        for (var name in data) {
            arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
        }
        arr.push(("ver=" + Math.random()).replace(".", ""));
        return arr.join("&");
    }
}

export let msgTout = null;
/**
 * Tips提示消息
 * @param msg
 * @param duration
 * @constructor
 */
export const Tips = (msg = '未获取到信息', duration = 3) => {
    var msgObj = document.querySelector('.tips'),
        msgSpan = msgObj ?
        msgObj.querySelector('span') :
        null;
    if (msgObj == undefined) {
        msgObj = document.createElement('div');
        msgSpan = document.createElement('span');
        msgObj.appendChild(msgSpan);
        msgObj.className = 'tips';
        document.body.appendChild(msgObj);
    }
    msgSpan.innerHTML = msg;
    msgObj.style.bottom = '10rem';
    msgObj.style.display = 'block';
    setTimeout(() => {
        msgObj.style.bottom = '11rem';
        msgObj.style.opacity = '1';
    }, 10);
    clearTimeout(msgTout);
    if (duration == 0)
        return;
    if (msg == '关闭')
        msgObj.style.display = 'none';
    msgTout = setTimeout(function() {
        msgObj.style.display = 'none';
        msgObj.style.bottom = '10rem';
        msgObj.style.opacity = '0';
    }, duration * 1000);
};

/**
 * 获取blob对象的兼容性写法
 * @param buffer
 * @param format
 * @param filename
 * @returns {*}
 */
export const getBlob = (buffer, format, filename) => {
    try {
        return new Blob(buffer, {
            type: format,
            filename
        });
    } catch (e) {
        var bb = new(window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
        buffer.forEach(function(buf) {
            bb.append(buf);
        });
        return bb.getBlob(format);
    }
};

/**
 * 压缩图片
 * @param data
 * @param callback
 * @returns {boolean}
 */
export const imgUpload = (data, callback) => {
    Tips('正在添加图片', 1);
    var inputObj = document.getElementById(data.inputId);
    var imgObj = document.getElementById(data.imgId);
    var index = data.index == undefined ? 0 : data.index;
    data.size == data.size ? data.size : 10;
    if (inputObj.files && inputObj.files[index]) {
        var orientation = null;
        EXIF.getData(inputObj.files['' + index + ''], function() {
            // alert(EXIF.pretty(this));
            EXIF.getAllTags(this);
            //alert(EXIF.getTag(this, 'Orientation'));
            orientation = EXIF.getTag(this, 'Orientation');
            //return;
        });

        var fr = new FileReader();
        fr.onload = function() {
            image.src = fr.result;
        };
        var file = inputObj.files[index];
        fr.readAsDataURL(inputObj.files[index]);
        var image = new Image();
        image.onload = function(event) {
            if (typeof data.scale != 'undefined' && data.scale != '') {
                var scaleW = data.scale.split(':')[0];
                var scaleH = data.scale.split(':')[1];
                if (image.width / scaleW != image.height / scaleH) {
                    inputObj.value = imgObj.src = '';
                    callback(false, '请按图片比例上传（' + data.scale + '）！');
                    return;
                }
            } else {
                var tips = '';
                var valid = true;
                if (typeof data.width != 'undefined' && data.width != '' && image.width != data.width) {
                    tips = '宽度：' + data.width + 'px，';
                    valid = false;
                }
                if (typeof data.height != 'undefined' && data.height != '' && image.height != data.height) {
                    tips += '高度：' + data.height + 'px，';
                    valid = false;
                }
                if (!valid) {
                    inputObj.value = imgObj.src = '';
                    callback(false, '请按图片尺寸上传(' + tips.substr(0, tips.length - 1) + ')');
                    return;
                }
            }
            if (typeof data.size != 'undefined' && data.size != '' && inputObj.files[index].size / 1024 / 1024 > data.size) {
                var sizeLimit = data.size + 'M';
                if (data.size < 1) {
                    sizeLimit = (data.size * 1024).toFixed(0) + 'KB';
                }
                inputObj.value = imgObj.src = '';
                callback(false, '请上传小于 ' + sizeLimit + ' 的图片');
                return;
            }
            var filename = file.name;
            var imgSize = image.src.length;
            // var imgUrl = window.URL.createObjectURL(inputObj.files[index]);
            // console.log(imgUrl);
            // console.log(image.src);
            imgObj.src = image.src;

            //图片压缩
            imgCompress(image.src, imgSize, data.presWidth, data.presQuality, orientation, function(baseStr) {
                //base64转二进制流图片
                var text = window.atob(baseStr.split(",")[1]);
                var aBuffer = new window.ArrayBuffer(baseStr.length);
                var buffer = new Uint8Array(aBuffer);
                var pecent = 0,
                    loop = null;
                for (var i = 0; i < text.length; i++) {
                    buffer[i] = text.charCodeAt(i);
                }
                var imgType = baseStr.split(';')[0].split(':')[1];
                var blob = getBlob([buffer], imgType);
                blob.filename = filename;
                callback(true, blob);
                //下载图片查看
                // var link = document.createElement('a');
                // link.href = window.URL.createObjectURL(blob);
                // link.download = filename;
                // link.click();
                // window.URL.revokeObjectURL(link.href);
            });
        };
    } else {
        //IE下，使用滤镜处理，给定宽高
        inputObj.select();
        var imgSrc = document.selection.createRange().text;
        var localImagId = document.getElementById(data.imgIeId);
        //设置初始大小
        var ieWidth = ieHeight = 100;
        if (typeof data.width != 'undefined' && !isNaN(data.width))
            ieWidth = data.width;
        if (typeof data.height != 'undefined' && !isNaN(data.height))
            ieHeight = data.height;
        localImagId.style.width = ieWidth + "px";
        localImagId.style.height = ieHeight + "px";
        //图片异常的捕捉，防止用户修改后缀来伪造图片
        try {
            localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
            localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
        } catch (e) {
            callback('请选择正确的图片格式!');
            return false;
        }
        imgObj.style.display = 'none';
        document.selection.empty();
    }
};

/**
 * 图片压缩
 * @param imgUrl
 * @param initSize
 * @param setWidth
 * @param quality
 * @param callBack
 * @param orientation
 */
export const imgCompress = (imgUrl, initSize, setWidth = 800, quality = 0.8, orientation, callBack) => {
    var setHeight,
        canvas = document.createElement('canvas'),
        context = canvas.getContext('2d'),
        img = new Image();
    img.src = imgUrl;
    img.onload = function() {
        if (initSize / 1024 < 200) {
            setWidth = img.width;
            setHeight = img.height;
        } else {
            if (setWidth > img.width)
                setWidth = img.width;
            setHeight = img.height / img.width * setWidth;
        }
        canvas.width = setWidth;
        canvas.height = setHeight;
        context.drawImage(img, 0, 0, setWidth, setHeight);
        var basestr = null;
        if (navigator.userAgent.match(/iphone/i)) {
            //如果方向角不为1，都需要进行旋转 added by lzk
            if (orientation != "" && orientation != 1) {
                // alert('旋转处理');
                switch (orientation) {
                    case 6: //需要顺时针（向左）90度旋转
                        // alert('需要顺时针（向左）90度旋转');
                        rotateImg(this, 'left', canvas);
                        break;
                    case 8: //需要逆时针（向右）90度旋转
                        // alert('需要顺时针（向右）90度旋转');
                        rotateImg(this, 'right', canvas);
                        break;
                    case 3: //需要180度旋转
                        // alert('需要180度旋转');
                        rotateImg(this, 'right', canvas); //转两次
                        rotateImg(this, 'right', canvas);
                        break;
                }
            }
            // basestr = canvas.toDataURL("image/jpeg", quality);
        }
        basestr = canvas.toDataURL('image/jpeg', quality); //后面的小数表示图片的质量
        var newSize = basestr.length;
        // alert(newSize);
        console.log('oldSize：' + initSize);
        console.log('newSize：' + newSize);
        console.log('percent：' + (newSize * 100 / initSize).toFixed(2) + '%');
        callBack(basestr);
    }
};


/**
 * 图片旋转
 * @param img
 * @param direction
 * @param canvas
 */
export const rotateImg = (img, direction, canvas) => {
    //最小与最大旋转方向，图片旋转4次后回到原方向
    var min_step = 0;
    var max_step = 3;
    if (img == null) {
        return;
    }
    //img的高度和宽度不能在img元素隐藏后获取，否则会出错
    var setHeight = null;
    var setWidth = 800;
    if (setWidth > img.width)
        setWidth = img.width;
    setHeight = img.height / img.width * setWidth;
    // canvas.width = setWidth;
    // canvas.height = setHeight;
    var step = 2;
    if (step == null) {
        step = min_step;
    }
    if (direction == 'right') {
        step++;
        //旋转到原位置，即超过最大值
        step > max_step && (step = min_step);
    } else {
        step--;
        step < min_step && (step = max_step);
    }
    //旋转角度以弧度值为参数
    var degree = step * 90 * Math.PI / 180;
    var ctx = canvas.getContext('2d');
    switch (step) {
        case 0:
            canvas.width = setWidth;
            canvas.height = setHeight;
            ctx.drawImage(img, 0, 0, setWidth, setHeight);
            break;
        case 1:
            canvas.width = setHeight;
            canvas.height = setWidth;
            ctx.rotate(degree);
            ctx.drawImage(img, 0, -setHeight, setWidth, setHeight);
            break;
        case 2:
            canvas.width = setWidth;
            canvas.height = setHeight;
            ctx.rotate(degree);
            ctx.drawImage(img, -setWidth, -setHeight, setWidth, setHeight);
            break;
        case 3:
            canvas.width = setHeight;
            canvas.height = setWidth;
            ctx.rotate(degree);
            ctx.drawImage(img, -setWidth, 0, setWidth, setHeight);
            break;
    }
};

/**
 * 加载图片
 * @type {string}
 */

/**
 * 图片上传(地址、方法)
 * @param file
 * @param callBack
 */
export const AjaxUploadImg = (file, callBack) => {
    let data = new FormData();
    if (file instanceof Array) {
        for (let i = 0; i < file.length; i++) {
            data.append('Filedata[]', file[i].msg, file[i].msg.filename);
        }
    } else {
        data.append('Filedata[]', file, file.filename);
    }

    $.ajax({
        // url: phpUrl + '/php/fileuploadUUID.php?AppId=0&AppCode=0&UserName=public', //线上地址
        url: phpUrl + '/php/fileuploadUUID.php', //内网地址
        // url: phpUrl + '/php/fileuploadUUID.php?AppId=0&AppCode=0&UserName=public&record=true',
        type: 'POST',
        data: data,
        cache: false,
        contentType: false, //不可缺
        processData: false, //不可缺
        success: function(res) {
            let status = res.split(':')[0],
                msg = res.split(':')[1];
            if (msg.indexOf(',') == 0) {
                msg = msg.substring(1, msg.length);
            }
            callBack({
                status,
                msg
            })
        }
    })
};

/**
 * 图片懒加载
 * @param elemet
 */
export const lazyLoad = (elemet) => {
    var lazyLoadImg = new LazyLoadImg({
        el: elemet,
        mode: 'default', //默认模式，将显示原图，diy模式，将自定义剪切，默认剪切居中部分
        time: 100, // 设置一个检测时间间隔
        complete: true, //页面内所有数据图片加载完成后，是否自己销毁程序，true默认销毁，false不销毁
        position: { // 只要其中一个位置符合条件，都会触发加载机制
            top: 0, // 元素距离顶部
            right: 0, // 元素距离右边
            bottom: 0, // 元素距离下面
            left: 0 // 元素距离左边
        },
        before: function() { // 图片加载之前执行方法

        },
        success: function(el) { // 图片加载成功执行方法
            if (el.parentNode.className == 'photo' || el.parentNode.className == 'showImg_div') {
                el.parentNode.style.backgroundImage = "url(" + el.src + ")";
            }
            el.classList.add('success')
        },
        error: function(el) { // 图片加载失败执行方法
            el.src = splitImg; //图裂
            if (el.parentNode.className == 'photo' || el.parentNode.className == 'showImg_div') {
                el.parentNode.style.backgroundImage = "url(" + splitImg + ")";
            }
        }
    });
    // lazyLoadImg.start() // 重新开启懒加载程序
    // lazyLoadImg.destroy() // 销毁图片懒加载程序
};

/**
 * URL获取关键字内容
 * @param keyName
 * @param newStr
 * @returns {string}
 */
export const urlKey = (keyName, newStr = location.href) => {
    var reg = new RegExp(keyName + '=([^&]*)(&|$)', 'i');
    var keyValue = reg.test(newStr) ?
        reg.exec(newStr)[1] :
        '';
    return keyValue.replace(/\s/ig, '');
};

/**
 * xmlToJson
 * @param xmlStr
 */
export const xmlToJson = (xmlStr) => {
    var xotree = new XML.ObjTree();
    var dumper = new JKL.Dumper();
    var tree = xotree.parseXML(xmlStr);
    var jsonStr = dumper.dump(tree);
    return jsonStr;
};

/**
 * 判断访问终端
 * @returns {{trident: boolean, presto: boolean, webKit: boolean, gecko: boolean, mobile: boolean, ios: boolean, android: boolean, iPhone: boolean, iPad: boolean, webApp: boolean, weixin: boolean, qq: boolean}}
 */
export const browser = () => {
    let u = navigator.userAgent;
    let version = {
        trident: u.indexOf('Trident') > -1, //IE内核x
        presto: u.indexOf('Presto') > -1, //opera内核
        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
        iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
        iPad: u.indexOf('iPad') > -1, //是否iPad
        webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
        weixin: u.indexOf('MicroMessenger') > -1, //是否微信
        qq: u.match(/\sQQ/i) == " qq" //是否QQ
    };
    return version
};

//ios键盘事件
export let oldScrollTop = 0
export const iosfocus = () => {
    if (browser().ios) {
        oldScrollTop = document.body.scrollTop
        clearInterval(sessionStorage.interval)
        delete sessionStorage.interval
        $("body").on("touchmove", function(event) {
            event.preventDefault;
        }, false)
        if (navigator.userAgent.indexOf('11_') > -1)
            return
        sessionStorage.interval = setInterval(() => {
            document.body.scrollTop = 99999999
        }, 1000)
    }
}
export const iosblur = () => {
    if (browser().ios) {
        clearInterval(sessionStorage.interval)
        delete sessionStorage.interval
        document.body.scrollTop = oldScrollTop
        $("body").off("touchmove")
    }
}


/**
 * 加载班级列表
 * @type {Array}
 */
export let classData = [];
export const getClassList = callback => {
    if (classData.length != 0) {
        callback(classData);
        return;
    }

    HttpService.query({
        url: '/jxt-commonbackground/ajaxLoaderSchoolOrgnization.do',
        data: {
            jybTicket: sessionStorage.ticket,
            method: 'ajaxJybJSON_LoadMyRelativeGrades'
        },
        async: false,
        success: (res => {
            if (res.code == 0) {
                let classList = [];
                res.rs.map((item) => {
                    if (item.children)
                        item.children.map((child) => {
                            let name = item.name + child.name;
                            if (child.name.indexOf(item.name) > -1)
                                name = child.name;
                            classList.push({
                                id: child.id,
                                name
                            })
                        })
                });
                classData = classList;
                callback(classList)
            } else {
                callback([]);
                Tips('未查询到班级')
            }
        })
    })
};

/**
 * 获取用户头像
 */
export const getDefaultImg = () => {
    if (sessionStorage.userrole == '家长') {
        return parent_default;
    } else {
        return teacher_default;
    }
};

/**
 * 家校通入口获取数据
 */
export const jxtLocalStorage = () => {
    sessionStorage.clear();
    sessionStorage.wherefrom = urlKey('wherefrom');
    sessionStorage.phone = urlKey('phone');
    sessionStorage.userphone = urlKey('userphone');
    sessionStorage.ticket = urlKey('ticket');
    sessionStorage.userrole = decodeURIComponent(urlKey('userrole'));
    sessionStorage.orgid = urlKey('orgid');
    sessionStorage.orgname = decodeURIComponent(urlKey('orgname'));
    sessionStorage.userid = urlKey('userid'); //随寻通babyid
    sessionStorage.appToken = urlKey('appToken'); //随寻通token
    sessionStorage.appType = urlKey('appType'); //1家长 2班主任 3教师
    sessionStorage.appback = urlKey('appback'); //app返回箭头0表示不显示，1表示返回
    sessionStorage.username = decodeURIComponent(urlKey('username'));
    // sessionStorage.record = urlKey('record'); //使用作业添加录音
    sessionStorage.video = urlKey('video'); //使用作业添加视频
    sessionStorage.babyid = urlKey('babyid'); //使用作业添加录音
    sessionStorage.accountid = urlKey('accountid'); //使用获取通讯录
    if (sessionStorage.appType != '')
        sessionStorage.userrole = ['家长', '班主任', '教师'][sessionStorage.appType - 1];
        localStorage.jxtUrlData = location.hash.split('?')[1]
    if (sessionStorage.wherefrom == 'weixin') {
        sessionStorage.weixin = true;
    } else {
        sessionStorage.app = true;
    }

    // if (sessionStorage.wherefrom == 'ios') {
    //     let version = urlKey('version'); //版本号
    //     if (version != '') {
    //         version = parseInt(version.replace(/[.]/g, ''))
    //         if (version < 142)
    //             delete sessionStorage.record
    //     } else {
    //         delete sessionStorage.record
    //     }
    // }
};

/**
 * 页面对应名称
 * @type {{addalbum: string, addgrowthrecord: string, addphoto: string, albumdetail: string, applyleave: string, classalbum: string, growthrecord: string, growthrecorddetails: string, index: string, : string, leavedetail: string, leavelist: string, notice: string, ntcdetail: string, ntcdetailfile: string, phonedirectories: string, score: string, scoredetail: string, subjecttimetable: string, task: string, taskdetail: string, taskpublish: string, punktemall: string, yasktoday: string, punktemyself: string, umtauschen: string, news: string}}
 */
export const pageNameList = {
    "addalbum": "相册新增",
    "addgrowthrecord": "成长记录新增",
    "addphoto": "照片新增",
    "albumdetail": "相册详情",
    "applyleave": "请假申请",
    "classalbum": "班级相册",
    "companyinfo": "商家介绍",
    "growthrecord": "成长记录",
    "growthrecorddetails": "成长记录详情",
    "index": "登录",
    "info": "资讯",
    "infodetail": "资讯详情",
    "integral": "园丁园",
    "integralinfo": "介绍",
    "integralmyself": "我的荣誉值",
    "leavedetail": "请假详情",
    "leavelist": "请假列表",
    "login": "登录",
    "": "登录",
    "more": "更多",
    "myorder": "我的订单",
    "mypackage": "我的卡券",
    "news": "最新动态",
    "notice": "校内公告",
    "ntcdetail": "公告详情",
    "ntcdetailfile": "附件查看",
    "orderdetail": "订单详情",
    "packagedetail": "卡券详情",
    "phonedirectories": "通讯录",
    "productdetails": "商品详情",
    "score": "成绩查询",
    "scoredetail": "成绩详情",
    "subjecttimetable": "班级课表",
    "task": "家庭作业",
    "taskdetail": "家庭作业详情",
    "taskpublish": "家庭作业发布",
    "tasktoday": "今日任务",
    "test": "测试",
    "umtauschen": "兑换记录"
};

/**
 * 全站数据缓存
 * @type {{}}
 */
export let localData = {};

/**
 * 图片全屏查看
 * @param src
 * @param e
 */
export const viewerImg = (src = 'src', e) => {
    if (sessionStorage.wxinit == 1) {
        var srcList = [];
        var thisSrc = e.currentTarget.getAttribute('src');
        if (location.href.toLowerCase().indexOf('albumdetail') > -1) { //判断是否相册
            var imgsObj = $(e.currentTarget).parents('.photos')
            $(imgsObj).find('img').each(function(item, index) {
                srcList.push($(this).attr('src'))
            })
        } else {
            srcList[0] = thisSrc
        }
        wx.previewImage({
            current: thisSrc,
            urls: srcList
        });
        return
    }
    let ele = '',
        url = '';
    if (typeof e == 'string') {
        ele = src;
        url = e;
    } else {
        ele = e;
        url = src;
    }
    let options = {
        'top': '0', // zoom target container top position in pixel
        'left': '0', // zoom target container left position in pixel
        'width': '100%', // zoom target container width in pixel or in percent
        'height': '100%', // zoom target container height in pixel or in percent
        'easing': 'smartZoomEasing', // $ easing function used when the browser doesn't support css transitions
        'maxScale': 10, // 放大的倍数
        'dblClickMaxScale': 1.8, // the max scale that will be applied on the zoom target on double click
        'mouseEnabled': true, // enable plugin mouse interaction
        'scrollEnabled': true, // enable plugin mouse wheel behviour
        'dblClickEnabled': true, // enable plugin mouse doubleClick behviour
        'mouseMoveEnabled': true, // enable plugin target drag behviour
        'moveCursorEnabled': true, // show moveCursor for drag
        'touchEnabled': true, // enable plugin touch interaction
        'dblTapEnabled': true, // enable plugin double tap behaviour
        'pinchEnabled': true, // enable zoom when user pinch on target
        'touchMoveEnabled': true, // enable target move via touch
        'containerBackground': '#000', // zoom target container background color (if containerClass is not set)
        'containerClass': 'zoomableContainer' // class to apply to zoom target container if you whant to change background or borders (don't change size or position via css)
    };
    $('body').css('overflow', 'hidden');
    $('html').css('overflow', 'hidden');


    // var t, l, w, h;
    // if (document.documentElement && document.documentElement.scrollTop) {
    //     t = document.documentElement.scrollTop;
    //     l = document.documentElement.scrollLeft;
    //     w = document.documentElement.scrollWidth;
    //     h = document.documentElement.scrollHeight;
    // } else if (document.body) {
    //     t = document.body.scrollTop;
    //     l = document.body.scrollLeft;
    //     w = document.body.scrollWidth;
    //     h = document.body.scrollHeight;
    // }
    var bro = browser(),
        scrollTop = $(document).scrollTop();
    if (bro.android) {
        $('.list').css('display', 'none');
    }
    let img = ele.target.getAttribute(url) == '' ? splitImg : ele.target.getAttribute(url);
    $(document.body).append('<div class="zoomShowImg" style="position: fixed;height: 100%;width: 100%;z-index: 100;top: 0;background: #000000;overflow: hidden"><img src="' + img + '" id="showImg"/></div>');
    $('#showImg').smartZoom(options);
    $('.zoomShowImg').on('click', '.zoomableContainer', function() {
        $('body').css('overflow', 'visible');
        $('html').css('overflow', 'visible');
        if (bro.android) {
            $('.list').css('display', 'block');
            $("html,body").animate({
                scrollTop: scrollTop
            }, 0);
        }
        $('.zoomShowImg').remove();
    });
    document.querySelector('#showImg').addEventListener('error', function(e) {
        e.target.src = splitImg;
    })
    // let viewer = new Viewer(ele.target, {
    //     url: url,
    //     button: false,
    //     toolbar: false,
    //     title: false,
    //     navbar: false,
    //     transition: true,
    //     viewed: function() {
    //         document.querySelector('.viewer-in').onclick = function() {
    //             viewer.hide();
    //         };
    //         document.querySelector('.viewer-canvas').onclick = function() {
    //             viewer.hide();
    //         };
    //     }
    // });
};
/**
 * 缩放显示图片
 * @param src
 * @param e
 */
export const zoomShowImg = (src = 'src', e) => {
    let ele = '',
        url = '';
    if (typeof e == 'string') {
        ele = src;
        url = e;
    } else {
        ele = e;
        url = src;
    }
    $(document.body).append('<div class="zoomShowImg" style="position: fixed;height: 100%;width: 100%;z-index: 10;top: 0;background: #000000;"><img src="' + ele.target.getAttribute(url) + '" id="showImg"/></div>');
    $('#showImg').smartZoom({
        'containerClass': 'zoomableContainer'
    });
    $('.zoomShowImg').on('click', '.zoomableContainer', function() {
        $('.zoomShowImg').parent.remove();
    });
};

/**
 * 显示加载动画
 * @param time
 * @param callback
 */
export const showLoading = (time, callback) => {
    if (!document.querySelector('#pageLoding'))
        $(document.body).append("<div class='pageLoding' id='pageLoding'> <div class='model_layout_loding'></div> <div class='lodingMain'><img src='" + loadImgUrl + "' alt=''> </div> </div>");
    $(".pageLoding").show();
    if (callback)
        callback(true); //回调
};

/**
 * 隐藏加载动画
 * @param time
 * @param callback
 */
export const showHiding = (time = 500, callback) => {
    $(".pageLoding").fadeOut(time);
    if (callback)
        callback(true); //回调
};

/**
 * 下拉刷新
 * obj:对象
 * contentObj:对象(里面的内容)
 * statusObj:对象(状态)
 * topMax:距顶部最大值
 * callback:回调data={status:'状态',top:'当前距离顶部高度'}
 */
export const pullDownRefresh = (obj, contentObj, statusObj, topMax, callback) => {
    //contentObj.style.position = 'absolute';
    var touchStart = 0,
        touchDis = 0,
        time, touch, value, top;
    obj.addEventListener('touchstart', function(event) {
        statusObj.style.display = 'block';
        statusObj.children[0].innerHTML = '下拉刷新';
        statusObj.children[0].className = '';
        touchStart = event.targetTouches[0].pageY;
    }, false);
    obj.addEventListener('touchmove', function(event) {
        statusObj.style.display = 'block';
        touch = event.targetTouches[0];
        var mTop = contentObj.style.paddingTop ? parseInt(contentObj.style.paddingTop) : 0
        value = mTop + touch.pageY - touchStart;
        callback({
            status: 'move',
            top: value
        });
        if (value < 0)
            return
        if (value > topMax - 20) {
            statusObj.children[0].innerHTML = '松开加载';
            statusObj.children[0].className = 'active';
        }
        if (value > topMax)
            return
        statusObj.style.lineHeight = value + 'px'
        contentObj.style.paddingTop = value + 'px';
        touchStart = touch.pageY;
        touchDis = touch.pageY - touchStart;
    }, false);
    obj.addEventListener('touchend', function(event) {
        touchStart = 0;
        top = contentObj.style.paddingTop ? parseInt(contentObj.style.paddingTop) : 0
        callback({
            status: 'end',
            top: top
        });
        if (top > 0) {
            clearInterval(time);
            time = setInterval(function() {
                top = contentObj.style.paddingTop ? parseInt(contentObj.style.paddingTop) : 0
                contentObj.style.paddingTop = top - 2 + 'px';
                if (top <= 0) {
                    statusObj.style.display = 'none';
                    clearInterval(time);
                }
            }, 1)
        } else {
            statusObj.style.display = 'none';
        }
    }, false);
};


//账户检查
export const funcCheck = () => {
    sessionStorage.funcCheck = 1;
    if ($('.indexlist a').length == 0) {
        setTimeout(() => {
            funcCheck()
        }, 100)
        return
    }
    $('.indexlist a').each(function() {
        if ($(this).text() != '校内公告') {
            $(this).addClass('useno')
        }
    })
    $('.indexlist a').click(function() {
        if ($(this).text() != '校内公告') {
            Tips('当前帐号非任课老师<br/>部分功能无法使用')
            return false;
        }
    })
}

//任务执行
export const taskFinish = (name, callback) => {
    if (!(sessionStorage.appToken && name)) {
        callback(false, '')
        return
    }
    $.ajax({
        url: `${sxtUrl}/${sessionStorage.userrole=='家长'?'guardian':'teacherapp'}/credit/achieve`,
        type: 'get',
        cache: false,
        data: `token=${sessionStorage.appToken}&taskName=${name}&schoolName=${sessionStorage.orgname}`,
        success: function(res) {
            if (res.code == 60002) {
                const unit = sessionStorage.userrole == '家长' ? '积分' : '荣誉值'
                const config = {
                    title: name,
                    content: `<img class='cfmkb' src=${imgKb} /><br/><span class='color-orange'>+${res.data.num}${unit}</span>`,
                    cancelName: '知道了'
                };
                callback(true, config)
            } else {
                callback(false, '')
            }
        }
    })
}


//随机字符串
export const randomStr = (data = {}) => {
    let len = data.length ? data.length : 6;
    let str = [];
    const codes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    for (let i = 0; i < len; i++) {
        str.push(codes[Math.ceil(Math.random() * codes.length)])
    }
    return str.join('')
}

//统计调用(跨域)
export const addStatistics = (url) => {
    HttpService.query({
        url,
        async: false,
        data: {
            token: sessionStorage.appToken
        },
        success: (res => {
            // console.log(res);
        })
    })
}
